<template>
  <section class="todoapp">
    <Header :arr="list" @add="addFn"></Header>
    <Main @del="delFn" :arr="showList"></Main>
    <Footer
      :arr="list"
      @clear="clearDoneFn"
      @changeType="changeTypeFn"
    ></Footer>
  </section>
</template>

<script>
import Header from "./components/TodoHeader.vue";
import Main from "./components/TodoMain.vue";
import Footer from "./components/TodoFooter.vue";
// 样式引入 + 导入组件并注册使用
import "./styles/base.css";
import "./styles/index.css";

export default {
  components: {
    Header,
    Main,
    Footer,
  },
  data() {
    return {
      type: "all",
      list: JSON.parse(localStorage.getItem("todos")) || [],
      // list: [
      //   {
      //     id: 100,
      //     name: "吃饭",
      //     isDone: true,
      //   },
      //   {
      //     id: 201,
      //     name: "睡觉",
      //     isDone: false,
      //   },
      //   {
      //     id: 103,
      //     name: "打豆豆",
      //     isDone: true,
      //   },
      // ],
    };
  },
  methods: {
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    addFn(name) {
      this.list.unshift({
        id: +new Date(),
        name,
        isDone: false,
      });
    },
    clearDoneFn() {
      this.list = this.list.filter((item) => item.isDone === false);
    },
    changeTypeFn(type) {
      this.type = type;
    },
  },
  computed: {
    showList() {
      if (this.type === "active") {
        return this.list.filter((item) => item.isDone === false);
      } else if (this.type === "complete") {
        return this.list.filter((item) => item.isDone === true);
      } else {
        return this.list;
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todos", JSON.stringify(this.list));
      },
    },
  },
};
</script>
